package com.quanyan.travel.service.impl;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.travel.api.req.ReqIndexTravelList;
import com.quanyan.travel.api.resp.RespTravelIndex;
import com.quanyan.travel.component.cache.MyRedisTemplate;
import com.quanyan.travel.constants.OutdoorConstants;
import com.quanyan.travel.entity.*;
import com.quanyan.travel.entity.vo.*;
import com.quanyan.travel.mapper.*;
import com.quanyan.travel.service.TravelIndexService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zyq
 * Date: 2016/5/27 0027
 * Time: 13:37
 */
@Service("travelIndexService")
public class TravelIndexServiceImpl implements TravelIndexService {

    @Autowired
    TbIndexBannerMapper indexBannerMapper;

    @Autowired
    MyRedisTemplate redisTemplate;

    @Autowired
    TbOutdoorCategoryMapper outdoorCategoryMapper;

    @Autowired
    TbOutdoorDestinationMapper outdoorDestinationMapper;

    @Autowired
    TbOutdoorActivityMapper outdoorActivityMapper;

    @Autowired
    TbCityMapper cityMapper;

    @Autowired
    TbOutdoorActivityDestinationMapper outdoorActivityDestinationMapper;

    @Autowired
    VTravelUserDefinedMapper vTravelUserDefinedMapper;

    @Value("${cache_expire_time}")
    private Integer cache_expire_time;


    private static Logger log = LoggerFactory.getLogger(TravelIndexServiceImpl.class);

    @Override
    public APIResponse<RespTravelIndex> indexProperties() {

        RedisKey rk = new RedisKey(RedisConstants.OUTDOOR_FAMILY_KEY, OutdoorConstants.INDEX_CACHE_KEY);
        Object o = null;
        RespTravelIndex respTravelIndex = null;
        try {
            o = redisTemplate.get(rk);
        } catch (Exception e) {
            log.error("indexProperties查询缓存异常，key={},{}", rk.getRedisKey(), e.getMessage());
        }
        respTravelIndex = (RespTravelIndex) o;
        if (respTravelIndex == null
                || (respTravelIndex.getBanners() == null || respTravelIndex.getBanners().size() == 0)
                || (respTravelIndex.getCategories() == null || respTravelIndex.getCategories().size() == 0)
                || (respTravelIndex.getDestinations() == null || respTravelIndex.getDestinations().size() == 0)) {
            log.info("indexProperties查询缓存为空或者数据不合法，重新查询数据库！");
            respTravelIndex = new RespTravelIndex();
            TbIndexBannerExample indexBannerExample = new TbIndexBannerExample();
            TbIndexBannerExample.Criteria indexBannerCriteria = indexBannerExample.createCriteria();
            indexBannerCriteria.andTypeEqualTo((byte) 1);
            indexBannerCriteria.andIsDeleteEqualTo((byte) 0);
            List<TbIndexBanner> banners = indexBannerMapper.selectByExample(indexBannerExample);
            List<Banner> bannerList = Lists.newArrayList();
            if (banners != null && banners.size() > 0) {
                for (TbIndexBanner tbIndexBanner : banners) {
                    Banner banner = new Banner();
                    BeanUtils.copyProperties(tbIndexBanner, banner);
                    banner.setActivityId(tbIndexBanner.getLinkId());
                    banner.setIndex(tbIndexBanner.getSequence());
                    bannerList.add(banner);
                }
            }
            respTravelIndex.setBanners(bannerList);

            TbOutdoorCategoryExample outdoorCategoryExample = new TbOutdoorCategoryExample();
            TbOutdoorCategoryExample.Criteria OutdoorCategoryCriteria = outdoorCategoryExample.createCriteria();
            OutdoorCategoryCriteria.andIsDeleteEqualTo(OutdoorConstants.IS_DELETE_FALSE);
            outdoorCategoryExample.setOrderByClause("priority DESC");
            List<TbOutdoorCategory> categories = outdoorCategoryMapper.selectByExample(outdoorCategoryExample);
            List<Category> categoryList = Lists.newArrayList();
            Category allType = new Category();
            allType.setCategoryId(0);
            allType.setExtendName("全部玩法");
            allType.setName("全部玩法");
            allType.setCategoryId(0);
            categoryList.add(allType);
            if (categories != null && categories.size() > 0) {
                for (TbOutdoorCategory tbOutdoorCategory : categories) {
                    Category category = new Category();
                    category.setCategoryId(tbOutdoorCategory.getId());
                    BeanUtils.copyProperties(tbOutdoorCategory, category);
                    categoryList.add(category);
                }
                respTravelIndex.setCategories(categoryList);
            }
            TbCityExample tbCityExample = new TbCityExample();
            TbCityExample.Criteria cityCriteria = tbCityExample.createCriteria();
            cityCriteria.andIsEnableEqualTo(1);
            cityCriteria.andIsActiveEqualTo(1);
            tbCityExample.setOrderByClause("priority DESC");
            List<TbCity> tbCities = cityMapper.selectByExample(tbCityExample);
            List<Destination> destinationList = Lists.newArrayList();
            Destination allDestination = new Destination();
            allDestination.setCityId(0);
            allDestination.setName("全部城市");
            allDestination.setAddress("全部城市");
            allDestination.setId(0);
            destinationList.add(allDestination);
            if(tbCities != null && tbCities.size() > 0){
                for(TbCity city : tbCities){
                    Destination destination = new Destination();
                    BeanUtils.copyProperties(city,destination);
                    destination.setCityId(city.getId());
                    destinationList.add(destination);
                }
            }
            respTravelIndex.setDestinations(destinationList);
            redisTemplate.setWithExpireTime(rk, respTravelIndex,cache_expire_time);
        }
        return APIResponse.returnSuccess(respTravelIndex);
    }

    @Override
    public APIResponse<PageObj<List<BaseActivity>>> indexActivities(ReqIndexTravelList request) {
        Integer pageNo = 1;
        Integer pageSize = OutdoorConstants.DEFAULT_PAGE_SIZE;
        if (request != null) {
            pageNo = request.getPageNo();
            pageSize = request.getPageSize();
        }
        TbOutdoorActivityExample tbOutdoorActivityExample = new TbOutdoorActivityExample();
        TbOutdoorActivityExample.Criteria criteria = tbOutdoorActivityExample.createCriteria();
        //获取cityid下的acitivtyId
        if(!request.getCityId().equals(0)){
            List<Integer> activityIds = vTravelUserDefinedMapper.getActivityIds(request.getCityId());
            if(CollectionUtils.isEmpty(activityIds)){
                return APIResponse.returnSuccess(null);
            }
            criteria.andIdIn(activityIds);
        }

        if(!request.getCategoryId().equals(0)){//0 :查询所有玩法
            criteria.andOutdoorCategoryIdEqualTo(request.getCategoryId());
        }
        if (null != request.getSortType() && !request.getSortType().equals(0)) {
            if (request.getSortType().equals(1)) {
                tbOutdoorActivityExample.setOrderByClause("price ASC");
            } else if (request.getSortType().equals(2)) {
                tbOutdoorActivityExample.setOrderByClause("price DESC");

            } else if (request.getSortType().equals(3)) {
                criteria.andTypeEqualTo((byte) 0);
                tbOutdoorActivityExample.setOrderByClause("update_time DESC");
            } else if (request.getSortType().equals(4)) {
                criteria.andTypeEqualTo((byte) 1);
                tbOutdoorActivityExample.setOrderByClause("update_time DESC");
            }
        }else {
            tbOutdoorActivityExample.setOrderByClause("update_time DESC");
        }
        criteria.andIsIndexShowEqualTo(OutdoorConstants.INDEX_SHOW_TRUE);
        criteria.andIsDeleteEqualTo(OutdoorConstants.IS_NOT_DELETE);
        Integer totalCount = outdoorActivityMapper.countByExample(tbOutdoorActivityExample);
        tbOutdoorActivityExample.setPage(new Page((pageNo) * pageSize, pageSize, totalCount));
        List<TbOutdoorActivity> tbOutdoorActivities = outdoorActivityMapper.selectByExample(tbOutdoorActivityExample);
        List<BaseActivity> list = Lists.newArrayList();
        if (tbOutdoorActivities != null && tbOutdoorActivities.size() > 0) {
            for (TbOutdoorActivity vOutdoorActivityPreview : tbOutdoorActivities) {
                //更新时间和场次信息
                BaseActivity baseActivity = new BaseActivity();
                BeanUtils.copyProperties(vOutdoorActivityPreview, baseActivity);
                Integer activityTime = vOutdoorActivityPreview.getActivityTime();
                Integer day  = Math.round(activityTime / 24);
                if(day == 0){
                    day = 1;
                }
                baseActivity.setDayNum(String.valueOf(day));
                Gson gson = new Gson();
                MultiMedia multiMedia = gson.fromJson(vOutdoorActivityPreview.getMultiMedia(), MultiMedia.class);
                baseActivity.setMultiMedia(multiMedia);
                baseActivity.setTag(baseActivity.getTag().split(",")[0]);
                List<DestinationVo> destinationVos = vTravelUserDefinedMapper.queryDestination(vOutdoorActivityPreview.getId());
                if (destinationVos != null && destinationVos.size() > 0) {
                    baseActivity.setAddress(destinationVos.get(0).getDestinationAddress());
                }
                if(vOutdoorActivityPreview.getType() == 1){
                    Integer id  = vTravelUserDefinedMapper.getActivityIdByActivityId(vOutdoorActivityPreview.getId());
                    String destination = vTravelUserDefinedMapper.getDestinationName(id);
                    baseActivity.setAddress(destination);
                }

                baseActivity.setDestinationList(destinationVos);
                if(baseActivity.getType() == 1){
                    //最低价格
                    double price = vTravelUserDefinedMapper.lowThemePrice(baseActivity.getId()).doubleValue();
                    baseActivity.setPrice(BigDecimal.valueOf(price));
                }
                list.add(baseActivity);
            }
            PageObj<List<BaseActivity>> result = PageObj.create(totalCount, pageNo, pageSize, list);
            return APIResponse.returnSuccess(result);
        } else {
            return APIResponse.returnSuccess(null);
        }
    }

}
